package com.lagou.homework.myZk.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.I0Itec.zkclient.ZkClient;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class DruidUtils {

    public static DataSource addConf(ZkClient zkClient, String path){
        String dbConfig = zkClient.readData(path);
        System.out.println("从zk中获取到sql配置为：" + dbConfig);
        String url = dbConfig.split("###")[0];
        String username = dbConfig.split("###")[1];
        String password = dbConfig.split("###")[2];

        DataSource dataSource = null;
        try {
            Map<String,String> dbConfigMap = new HashMap<>();
            dbConfigMap.put("url",url);
            dbConfigMap.put("username",username);
            dbConfigMap.put("password",password);
            dataSource = DruidDataSourceFactory.createDataSource(dbConfigMap);
        }  catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return dataSource;
    }

    // 获取连接的对象
    public static Connection getConnection(DataSource dataSource){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 5.释放资源
    public static void close(Connection connection, Statement statement){
        if (null != connection && null != statement){
            try {
                // 归还连接
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (null != connection && null != statement && null != resultSet){
            try {
                // 归还连接
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 每个数据库中的表名不一样，通过 show tables; 来验证连接到了新的数据库
    public static void showTablesName(DataSource dataSource){
        Connection con = DruidUtils.getConnection(dataSource);
        Statement statement = null;
        ResultSet re = null;
        try {
            statement = con.createStatement();
            re = statement.executeQuery("show tables");
            while (re.next()){
                System.out.println(re.getString(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DruidUtils.close(con,statement,re);
    }
}
